import logging
import pandas as pd
import numpy as np
import os
import json
from typing import List, Dict, Any, Optional, Tuple, Union
import threading
import concurrent.futures
from pathlib import Path
from datetime import datetime

# 修复导入问题
import sys
import os

sys.path.append(str(Path(__file__).resolve().parent.parent.parent))

from source.data_processor.utils.experiment_data import ExperimentData

from .metric.metric_detector import MetricDetector
from .trace.trace_detector import TraceDetector
# 导入新的检测结果类
from .metric.metric_detection_result import MetricDetectionResult
from .trace.trace_detector import TraceDetectionResult

logger = logging.getLogger(__name__)
log_lock = threading.Lock()

class DetectionManager:
    """
    统一异常检测管理器，协调并管理指标和链路的异常检测流程。
    
    该类作为异常检测的入口点，主要功能包括：
    1. 同时管理指标异常检测器(MetricDetector)和链路异常检测器(TraceDetector)
    2. 对故障案例进行检测并返回结果
    
    使用方法：
    1. 初始化DetectionManager，配置输出目录和检测器参数
    2. 调用detect_anomalies方法，传入ExperimentData对象
    3. 获取检测结果
    """
    
    def __init__(
        self,
        output_dir: str,
        metric_detector_params: Optional[Dict[str, Any]] = None,
        trace_detector_params: Optional[Dict[str, Any]] = None,
    ):
        """
        初始化异常检测管理器
        
        参数:
            output_dir: 检测结果输出目录
            metric_detector_params: 指标检测器参数
            trace_detector_params: 链路检测器参数
        """
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        # 创建指标和链路检测结果的子目录
        self.metric_output_dir = self.output_dir / "metric_anomalies"
        self.trace_output_dir = self.output_dir / "trace_anomalies"
        
        for dir_path in [self.metric_output_dir, self.trace_output_dir]:
            dir_path.mkdir(parents=True, exist_ok=True)
        
        # 初始化检测器实例
        self.metric_detector_params = metric_detector_params or {}
        self.trace_detector_params = trace_detector_params or {}
        
        self.metric_detector = MetricDetector(**self.metric_detector_params, output_dir=self.metric_output_dir)
        self.trace_detector = TraceDetector(**self.trace_detector_params, output_dir=self.trace_output_dir)
        
        logger.info(f"初始化异常检测管理器，输出目录: {self.output_dir}")
    
    def detect_anomalies(self, experiment_data: ExperimentData) -> Tuple[Optional[MetricDetectionResult], Optional[TraceDetectionResult]]:
        """
        对故障记录进行异常检测
        
        参数:
            experiment_data: 包含故障数据的ExperimentData对象
            
        返回:
            元组 (metric_result, trace_result)，包含指标和链路的检测结果
        """
        anomaly_id = experiment_data.anomaly_id
        logger.info(f"开始对故障 {anomaly_id} 进行异常检测")
        
        # 指标异常检测
        metric_result = None
        if hasattr(experiment_data, 'metrics_df') and not experiment_data.metrics_df.empty:
            try:
                metric_result = self.metric_detector.detect_anomalies(
                    experiment_data.metrics_df, 
                    experiment_data.observation_time, 
                    anomaly_id
                )
                logger.info(f"故障 {anomaly_id} 的指标异常检测已完成")
            except Exception as e:
                logger.error(f"故障 {anomaly_id} 的指标异常检测失败: {e}", exc_info=True)
        else:
            logger.warning(f"故障 {anomaly_id} 缺少指标数据，跳过指标异常检测")
        
        # 链路异常检测
        trace_result = None
        if hasattr(experiment_data, 'dependencies_df') and not experiment_data.dependencies_df.empty:
            try:
                trace_result = self.trace_detector.detect_anomalies(
                    experiment_data.dependencies_df,
                    anomaly_id
                )
                logger.info(f"故障 {anomaly_id} 的链路异常检测已完成")
            except Exception as e:
                logger.error(f"故障 {anomaly_id} 的链路异常检测失败: {e}", exc_info=True)
        else:
            logger.warning(f"故障 {anomaly_id} 缺少链路数据，跳过链路异常检测")
        
        logger.info(f"故障 {anomaly_id} 的异常检测已完成")
        return metric_result, trace_result
